package me.aurora.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import me.aurora.annotation.Log;
import me.aurora.config.AuroraProperties;
import me.aurora.domain.SysLog;
import me.aurora.domain.User;
import me.aurora.repository.SysLogRepo;
import me.aurora.util.AddressUtil;
import me.aurora.util.HttpContextUtils;
import me.aurora.util.IPUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

/**
 * 通过切面保存操作日志
 * @author 郑杰
 * @date 2018/08/22 16:41:33
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private AuroraProperties auroraProperties;

	@Autowired
	private SysLogRepo sysLogRepo;

	@Pointcut("@annotation(me.aurora.annotation.Log)")
	public void pointcut() {
	}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws JsonProcessingException {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        if(auroraProperties.getOpenAopLog()){
            saveLog(point, time);
        }
        return result;
    }

	private void saveLog(ProceedingJoinPoint joinPoint, long time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		SysLog sysLog = new SysLog();
		Log logAnnotation = method.getAnnotation(Log.class);
		if (logAnnotation != null) {
			// 注解上的描述
			sysLog.setOperation(logAnnotation.value());
		}
		// 请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		String username = null;
		sysLog.setMethod(className + "." + methodName + "()");
		// 请求的方法参数值
		Object[] args = joinPoint.getArgs();
		// 请求的方法参数名称
		LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
		String[] paramNames = u.getParameterNames(method);
		if (args != null && paramNames != null) {
			String params = "";
			for (int i = 0; i < args.length; i++) {
			    if("password".equals(paramNames[i])){
			        continue;
                }
                if("username".equals(paramNames[i])){
			        username = args[i]+"";
                }
				params += "  " + paramNames[i] + ": " + args[i];
			}
			sysLog.setParams(params);
		}
		// 获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		// 设置IP地址
		sysLog.setIp(IPUtils.getIpAddr(request));
		sysLog.setLocation(AddressUtil.getAddresses(sysLog.getIp()));
		// 用户名
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		sysLog.setUsername(user == null?"Login failed："+username:user.getUsername());
		sysLog.setTime((int) time);
		sysLogRepo.save(sysLog);
	}
}
